<?php
namespace app\common\model;

use think\Model;

class User extends Model
{
    protected $insert = ['create_time'];

    /**
     * 创建时间
     * @return bool|string
     */
    protected function setCreateTimeAttr()
    {
        return date('Y-m-d H:i:s');
    }

    /**
     * 查询一条用户信息
     *
     * @param array $params
     * @param bool $fields
     * @return array
     */
    public function getInfo(array $params, $fields = true)
    {
        $where = $return = [];

        if (isset($params['id']) && $params['id'] > 0) {
            $where['id'] = $params['id'];
        }

        if (isset($params['username']) && !empty($params['username'])) {
            $where['username'] = $params['username'];
        }

        if (!empty($where)) {
            $res = $this->where($where)->field($fields)->find();
            if (!empty($res)) {
                $return = $res->toArray();
            }
        }

        return $return;
    }

    /**
     * @param $id
     * @param array $req
     * @return bool
     */
    public function saveDate($id, array $req)
    {
        if ($id <= 0) {
            return false;
        }

        $data = $req;
        $res = $this->save($data, ['id' => $id]);
        // 清空原始数据，防止上一条对下一条的影响
        $this->origin = [];
        return $res;
    }

    /**
     * 添加一条记录
     *
     * @author mayy
     * @date 2017-10-10
     * @param array $data
     * @return  integer|boolean
     */
    public function addData(array $data)
    {
        $user_data = $data;
        $asset_data['create_time'] = NOW_DATE;

        $res = $this->allowField(true)->data($user_data,true)->isUpdate(false)->save();
        $return = ($res && isset($this->id) && $this->id > 0) ? $this->id : false;
        return $return;
    }
}